package com.sherllinhe.business.service;


import com.sherllinhe.business.domain.ConfirmOrder;
import com.sherllinhe.business.domain.DailyTrainSeat;
import com.sherllinhe.business.domain.DailyTrainTicket;
import com.sherllinhe.business.enums.ConfirmOrderStatusEnum;
import com.sherllinhe.business.feign.MemberFeign;
import com.sherllinhe.business.mapper.ConfirmOrderMapper;
import com.sherllinhe.business.mapper.DailyTrainSeatMapper;
import com.sherllinhe.business.mapper.cust.DailyTrainTicketMapperCust;
import com.sherllinhe.common.context.LoginMemberContext;
import com.sherllinhe.common.req.MemberTicketReq;
import com.sherllinhe.common.resp.CommonResp;
import com.sherllinhe.common.util.SnowUtil;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.sherllinhe.business.req.ConfirmOrderTicketReq;

import java.util.Date;
import java.util.List;

/**
 * 功能：
 * 作者：Sherllin He
 * 日期：
 */
@Slf4j
@Service
public class AfterConfirmOrderService {
    @Autowired
    private DailyTrainSeatMapper dailyTrainSeatMapper;
    @Autowired
    private DailyTrainTicketMapperCust dailyTrainTicketMapperCust;
    @Autowired
    private MemberFeign memberFeign;
    @Autowired
    private ConfirmOrderMapper confirmOrderMapper;

//    @Transactional
    @GlobalTransactional
    public void afterDoConfirm(List<DailyTrainSeat> finalSeatList, DailyTrainTicket dailyTrainTicket, List<ConfirmOrderTicketReq> tickets, ConfirmOrder confirmOrder) throws Exception {
        log.info("seata全局事务的ID：{}", RootContext.getXID());
        //更新每日座位的sell字段数据
        for (int j = 0; j < finalSeatList.size(); j++) {
            DailyTrainSeat seat = finalSeatList.get(j);
            DailyTrainSeat seatForUpdate = new DailyTrainSeat();
            seatForUpdate.setId(seat.getId());
            seatForUpdate.setSell(seat.getSell());
            seatForUpdate.setUpdateTime(new Date());
            dailyTrainSeatMapper.updateByPrimaryKeySelective(seatForUpdate);

            //将每日车票表受影响的余票数量扣减
            //假设10个车站(站序0-9)，本次买4-7站
            //那么sell就有9位，第一位表示从0站到1站，以此类推
            //原售：001000001
            //购买：000011100
            //新售：001011101
            //那么：影响的区间有XXX11111X，只要与4-7站有交集的，余票就要减1
            Integer startIndex = dailyTrainTicket.getStartIndex();
            Integer endIndex = dailyTrainTicket.getEndIndex();
            char[] chars = seatForUpdate.getSell().toCharArray();

            int minStartIndex = 0;
            for (int i = startIndex - 1; i >= 0; i--) {
                if (chars[i] == '1') {
                    minStartIndex = i + 1;
                    break;
                }
            }
            int minEndIndex = startIndex + 1;

            int maxStartIndex = endIndex - 1;

            int maxEndIndex = chars.length;
            for (int i = endIndex; i < chars.length; i++) {
                if (chars[i] == '1') {
                    maxStartIndex = i;
                    break;
                }
            }
            log.info("影响的出发站区间：{}-{}", minStartIndex, maxStartIndex);
            log.info("影响的到达站区间：{}-{}", minEndIndex, maxEndIndex);
            //0123
            //0-2
            //000
            //110
            //110
            //start:0-1
            //end:1-
            dailyTrainTicketMapperCust.updateCountBySell(dailyTrainTicket.getDate(),
                    dailyTrainTicket.getTrainCode(),
                    seat.getSeatType(),
                    minStartIndex,
                    maxStartIndex,
                    minEndIndex,
                    maxEndIndex);

            //调用会员接口，为会员增加一张车票
            MemberTicketReq req = new MemberTicketReq();
            req.setId(SnowUtil.getSnowflakeNextId());
            req.setMemberId(confirmOrder.getMemberId());
            req.setPassengerId(tickets.get(j).getPassengerId());
            req.setPassengerName(tickets.get(j).getPassengerName());
            req.setTrainDate(dailyTrainTicket.getDate());
            req.setTrainCode(dailyTrainTicket.getTrainCode());
            req.setCarriageIndex(seat.getCarriageIndex());
            req.setSeatRow(seat.getRow());
            req.setSeatCol(seat.getCol());
            req.setStartStation(dailyTrainTicket.getStart());
            req.setStartTime(dailyTrainTicket.getStartTime());
            req.setEndStation(dailyTrainTicket.getEnd());
            req.setEndTime(dailyTrainTicket.getEndTime());
            req.setSeatType(seat.getSeatType());
            CommonResp <Object> commonResp = memberFeign.save(req);
            log.info("调用/member/feign/ticket/save接口返回：{}", commonResp);
        }
        //更新confirm_order表的status字段值为成功
        ConfirmOrder confirmOrderForUpdate = new ConfirmOrder();
        confirmOrderForUpdate.setId(confirmOrder.getId());
        confirmOrderForUpdate.setStatus(ConfirmOrderStatusEnum.SUCCESS.getCode());
        confirmOrderForUpdate.setUpdateTime(new Date());
        confirmOrderMapper.updateByPrimaryKeySelective(confirmOrderForUpdate);

//        模拟被调用方出现异常
//        if(1==1){
//            throw new Exception("测试事务异常");
//        }

    }

}
